package com.atguigu.lease.common.springmvc;

import com.atguigu.lease.common.result.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.swing.*; /**
 * description: 全局异常处理
 *   回顾： 1.@ControllerAdvice @RestControllerAdvice
 *   2. 定义异常处理的方法即可 @ExceptionHandler(依赖类型.class)
 */
@RestControllerAdvice
//@ControllerAdvice + @ResponseBody。
public class GlobalExceptionHandlers {//Spring MVC 全局异常处理器
    //通过 @ExceptionHandler(Exception.class) 捕获所有未处理的异常
    /*
         public static Result<String> fail(String message) {
            Result<String> result = build(null);
            result.setCode(ResultCodeEnum.FAIL.getCode()); //201
            result.setMessage(message); //错误信息
            return result;
        }
     */
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception e){
        //记录日志
        e.printStackTrace();
        //返回异常信息
        return Result.fail(e.getMessage());
    }


    /*
         public static Result<String> fail(int code,String message) {
            Result<String> result = build(null);
            result.setCode(code); //201
            result.setMessage(message); //错误信息
            return result;
        }
     */
    //接收自定义异常，业务失败的场景
    @ExceptionHandler(LeaseException.class)
    public  Result<String> leaseExceptionHandler(LeaseException e){
        e.printStackTrace();
        return Result.fail(e.getCode(),e.getMessage());
    }

}
